#include "MySoundMgr.h"
#include "Tool.h"

CMySoundMgr::CMySoundMgr(void)
{
	m_apkBGM.clear();
	m_apkSoundEffects.clear();

	m_iBGMVolume = 300;
	m_iSoundEffectVolume = 300;
	m_iSoundEffectIndex = 0;

	for (int i = 0;i < SoundEffectMaxNum;i++)
	{
		m_apkSoundEffects.push_back(NULL);
	}
}

CMySoundMgr::~CMySoundMgr(void)
{
	std::map<string,CGameMusic*>::iterator kIter = m_apkBGM.begin();
	for (;kIter != m_apkBGM.end();kIter++)
	{
		SafeDelete(kIter->second);
	}
	m_apkBGM.clear();

	for (int i = 0;i < (int)m_apkSoundEffects.size();i++)
	{
		SafeDelete(m_apkSoundEffects[i]);
	}
	m_apkSoundEffects.clear();
}

void CMySoundMgr::PlayBGM( const string& rkPath,int iVolume /*= 300*/,BOOL bRepeat /*= TRUE*/ )
{
	CGameMusic* pkMusic = GetBGM(rkPath);
	if (pkMusic == NULL)
	{
		pkMusic = new CGameMusic(rkPath.c_str());
		if (pkMusic)
		{
			m_apkBGM[rkPath] = pkMusic;
			pkMusic->Play(iVolume,bRepeat);
		}
	}
	else
	{
		pkMusic->Play(iVolume,bRepeat);
	}

	return;
}

void CMySoundMgr::StopBGM( const string& rkPath )
{
	CGameMusic* pkMusic = GetBGM(rkPath);
	if (pkMusic)
	{
		pkMusic->Stop();
	}

	return;
}

void CMySoundMgr::PauseBGM( const string& rkPath )
{
	CGameMusic* pkMusic = GetBGM(rkPath);
	if (pkMusic)
	{
		pkMusic->Pause();
	}

	return;
}

void CMySoundMgr::ReStartBGM( const string& rkPath,int iVolume /*= 300*/,BOOL bRepeat /*= TRUE*/ )
{
	CGameMusic* pkMusic = GetBGM(rkPath);
	if (pkMusic)
	{
		pkMusic->Play(iVolume,bRepeat,TRUE);
	}

	return;
}

void CMySoundMgr::PlaySoundEffect( const string& rkPath,int iVolume /*= 300*/ )
{
	CGameMusic* pkMusic = new CGameMusic(rkPath.c_str());
	if (pkMusic == NULL)
	{
		return;
	}

	if (iVolume <= 0)
	{
		iVolume = m_iSoundEffectVolume;
	}

	pkMusic->Play(iVolume,FALSE);
	SafeDelete(m_apkSoundEffects[m_iSoundEffectIndex]);

	m_apkSoundEffects[m_iSoundEffectIndex] = pkMusic;
	m_iSoundEffectIndex++;
	if (m_iSoundEffectIndex >= SoundEffectMaxNum)
	{
		m_iSoundEffectIndex = 0;
	}

	return;
}

void CMySoundMgr::SetBGMVolume( int iVolume )
{
	m_iBGMVolume = iVolume;

	map<string,CGameMusic*>::iterator kIter = m_apkBGM.begin();
	for (kIter;kIter != m_apkBGM.end();kIter++)
	{
		if (kIter->second)
		{
			kIter->second->SetVolume(iVolume);
		}
	}

	return;
}

void CMySoundMgr::SetSoundEffectVolume( int iVolume )
{
	m_iSoundEffectVolume = iVolume;
	return;
}

CGameMusic* CMySoundMgr::GetBGM( const string& rkPath )
{
	map<string,CGameMusic*>::iterator kIter = m_apkBGM.begin();
	for (kIter;kIter != m_apkBGM.end();kIter++)
	{
		if (kIter->first == rkPath)
		{
			return kIter->second;
		}
	}

	return NULL;
}
